import os from "os";
import { cyan, green, bold } from "chalk";
import type { Compiler } from "webpack";

class ClientPlugin {
  apply(compiler: Compiler) {
    compiler.hooks.done.tap('ClientPlugin', (stats) => {
      const { port = 8080, server = {} } = stats.compilation.options.devServer as any;
      const networkInterfaces = os.networkInterfaces();
      let protocol = "http";
      let hostnameName;
      if(Object.prototype.toString.call(server) === "[object String]"){
        if(server && server.toLowerCase() == "https"){
          protocol = "https";
        }
      } else {
        if(server.type && server.type.toLowerCase() == "https"){
          protocol = "https";
        }
      }
      for (const iface of Object.values(networkInterfaces)) {
        if(iface){
          for (const config of iface) {
            if (config.family === 'IPv4' && !config.internal) {
              hostnameName = config.address;
            }
          }
        }
      }
      if(hostnameName){
        console.log(`${bold(green(`➜ Local: `))}${cyan(`${protocol}://localhost:${port}`)}`);
        console.log(`${bold(green(`➜ Network: `))}${cyan(`${protocol}://${hostnameName}:${port}\n`)}`);
      } else {
        console.log(`${bold(green(`➜ Local: `))}${cyan(`${protocol}://localhost:${port}`)}\n`);
      }
    });
  }
}

export default ClientPlugin;